<template>
  <el-upload class="avatar-uploader" action list-type="picture-card" :show-file-list="false" :http-request="uploadPic"
    :before-upload="beforePicUpload" :style="uploadStyle">
    <el-image v-if="imageUrl" :src="imageUrl" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon" />
    <span class="el-upload-list__item-delete" @click="handleRemove(file)">
      <i class="el-icon-delete"></i>
    </span>
    <div v-show="showTip" slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg/gif，且不超过2m</div>
  </el-upload>
</template>
<script>
import { upload } from '@/api/upload';

export default {
  name: 'ImgUpload',
  props: {
    showTip: {
      type: Boolean,
      default: true
    },
    imageUrl: {
      type: String,
      default: ''
    },
    width: {
      type: String,
      default: '100px'
    },
    height: {
      type: String,
      default: '100px'
    },
    cicle: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      allowFileType: 'jpg,png,jpeg,gif'
    };
  },
  computed: {
    uploadStyle() {
      return {
        '--width': this.width,
        '--height': this.height,
        '--cicle': this.cicle ? '50%' : 'none'
      }
    }
  },
  methods: {
    uploadPic(file) {
      const formData = new FormData();
      formData.append('file', file.file);
      upload(formData).then(response => {
        this.$emit('imageUrlChange', response.actionUrl);
      });
    },
    beforePicUpload(file) {
      if (!file.type) {
        this.$message.error('图片类型错误');
      }
      const fileExt = file.name.replace(/.+\./, '').toLowerCase();
      const isPic = this.allowFileType.includes(fileExt);
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isPic) {
        this.$message.error('上传图片只能是 jpg,png,gif,jpeg 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isPic && isLt2M;
    },
    handleRemove(file) {
      this.$emit('imageUrlChange', '');
    }
  }
};
</script>

<style lang="less" scoped>
.avatar-uploader ::v-deep .el-upload--picture-card {
  width: var(--width);
  height: var(--height);
  box-sizing: content-box;
  border: 1px solid #d9d9d9;
  border-radius: var(--cicle);
  justify-content: center;
  display: flex;
  align-items: center;

  .el-icon-plus .avatar-uploader-icon {
    line-height: var(--height);
  }
}

.avatar {
  line-height: var(--height);
  border-radius: var(--cicle);
  width: var(--width);
  height: var(--height);
}
</style>
